
import 'package:flame/collisions.dart';
import 'package:flame/game.dart';
import 'package:flame/events.dart';
import 'package:flame/sprite.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:study_demo/ui/game/touch_indicator.dart';
import 'package:study_demo/ui/game/xy_game5/bullet.dart';
import 'package:study_demo/ui/game/xy_game5/component.dart';

class Game5 extends FlameGame
    with HasCollisionDetection, KeyboardEvents, TapDetector, PanDetector {
  late final HeroComponent player;
  late final Monster monster;
  late final RectangleHitbox box;

  @override
  Future<void> onLoad() async {
    const String src = 'adventurer/animatronic.png';
    await images.load(src);
    var image = images.fromCache(src);
    SpriteSheet sheet =
        SpriteSheet.fromColumnsAndRows(image: image, columns: 13, rows: 6);
    int frameCount = sheet.rows * sheet.columns;
    List<Sprite> sprites = List.generate(frameCount, sheet.getSpriteById);
    SpriteAnimation animation =
        SpriteAnimation.spriteList(sprites, stepTime: 1 / 24, loop: true);
    Vector2 monsterSize = Vector2(64, 64);
    final double pY = size.y / 2;
    final double pX = size.x / 2;
    monster = Monster(
        animation: animation, size: monsterSize, position: Vector2(pX, pY));
    player = HeroComponent();
    box = RectangleHitbox()..debugMode = false;
    player.add(box..debugMode = false);
    add(player);
    add(monster);
  }

  @override
  void update(double dt) {
    super.update(dt);
    final Iterable<Bullet> bullets = children.whereType<Bullet>();
    for (Bullet bullet in bullets) {
      if (bullet.isRemoving) {
        continue;
      }
      if (monster.containsPoint(bullet.absoluteCenter)) {
        bullet.removeFromParent();
        monster.loss(50);
      }
    }
  }

  final double step = 10;

  double _counter = 0;

  @override
  void onTap() {
    player.shoot();
  }

  @override
  onTapCancel() {}

  @override
  onTapDown(TapDownInfo info) {}

  @override
  onTapUp(TapUpInfo info) {}

  @override
  void onPanStart(DragStartInfo info) {}

  double ds = 0;

  @override
  void onPanUpdate(DragUpdateInfo info) {
    ds += info.delta.global.length;
    if (ds > 10) {
      add(TouchIndicator(position: info.eventPosition.global));
      ds = 0;
    }
  }

  @override
  void onPanEnd(DragEndInfo info) {}

  @override
  void onPanCancel() {}

  // 键盘事件
  @override
  KeyEventResult onKeyEvent(
      KeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
    final isKeyDown = event is KeyDownEvent;
    if (event.logicalKey == LogicalKeyboardKey.keyJ && isKeyDown) {
      player.shoot();
    }
    return super.onKeyEvent(event, keysPressed);
  }
}
